import axios from 'axios'
import {
  ElMessage,
  ElLoading
} from 'element-plus';
//添加响应拦截器
axios.interceptors.response.use(res => {
  if (res.headers.accesstoken && res.headers.accesstoken !== localStorage.getItem('token')) {
    localStorage.setItem('token', res.headers.accesstoken)
  }
  return res
}, error => {
  // 响应状态码处理
  if (error.response.status == 401) {
    ElMessage.error(error.response.data.error_msg)
  }
  if (error.response.status == 403) {
    ElMessage.error(error.response.data.error_msg)
  }
  return Promise.reject(error)
})
//添加请求拦截器
axios.interceptors.request.use(
  (config: any) => {
    let hasAuthorization = localStorage.getItem('token') || ''
    config.headers.AccessToken = hasAuthorization
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
class Model {
  constructor() {
  }
  api(options: any = {}) {
    if (!options.method) options.method = 'get'
    if (options.domain) options.url = options.domain + options.url
    return new Promise((resolve, reject) => {
      let request = axios(options)
      request
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          throw new Error(error)
        })
    })
  }

  get(options: any = {}) {
    options.method = 'get'
    return this.api(options)
  }

  post(options: any = {}) {
    options.method = 'post'
    return this.api(options)
  }

  put(options: any = {}) {
    options.method = 'put'
    return this.api(options)
  }

  delete(options: any = {}) {
    options.method = 'delete'
    return this.api(options)
  }
}
export default Model